package com.mhc.suzuki.service.impl;

import com.alibaba.fastjson.JSON;
import com.mhc.haval.security.model.Role;
import com.mhc.haval.security.model.User;
import com.mhc.suzuki.bo.*;
import com.mhc.suzuki.constant.*;
import com.mhc.suzuki.dal.mapper.ext.CustomerExtMapper;
import com.mhc.suzuki.dal.model.*;
import com.mhc.suzuki.dal.query.*;
import com.mhc.suzuki.exception.SuzukiCommonException;
import com.mhc.suzuki.manager.*;
import com.mhc.suzuki.model.bo.CreditQueryApplyBO;
import com.mhc.suzuki.model.bo.OrderListBO;
import com.mhc.suzuki.service.AnnexListService;
import com.mhc.suzuki.service.LocationService;
import com.mhc.suzuki.service.OrderService;
import com.mhc.suzuki.vo.AnnexListVO;
import com.mhc.suzuki.vo.OrderVO;
import com.subaru.common.query.PageResult;
import com.subaru.common.util.BeanCopierUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Service
//@CacheConfig(cacheNames="SuzukiOrderCache")
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderManager orderManager;
    @Autowired
    private CustomerManager customerManager;
    @Autowired
    private OrderCustomerRelManager orderCustomerRelManager;
    @Autowired
    private CreditQueryApplyManager creditQueryApplyManager;
    @Autowired
    private HouseInfoManager houseInfoManager;
    @Autowired
    private EmergencyContactManager emergencyContactManager;
    @Autowired
    private LocationService locationService;
    @Autowired
    private CustomerExtMapper customerExtMapper;
    @Autowired
    private AnnexListService annexListService;

    /**
     * 创建订单，最多有3种角色，客户在当前订单中的角色，如主贷人，担保人(可以多个)，共同购车人等
     * @param creditQueryApplyBOList
     * @param terminalType
     * @param orderNo
     * @param user
     * @throws SuzukiCommonException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrder(List<CreditQueryApplyBO> creditQueryApplyBOList, String terminalType, String orderNo, User user) throws SuzukiCommonException {
        OrderDO orderDO = orderManager.selectByOrderNo(orderNo);
        if (orderDO != null) {
            throw new SuzukiCommonException(ErrorCodeEnum.ORDER_EXIST);
        }

        //插入用户信息end
        orderDO = new OrderDO();
        orderDO.setOrderNo(orderNo);

        //获取用户部门，公司信息
        orderDO.setDeptId(user.getDeptId());
        orderDO.setCompanyNo(user.getCompanyNo());

        //插入用户信息start
        for (CreditQueryApplyBO creditQueryApplyBO : creditQueryApplyBOList) {
            //附件批次号
            String annexBatchNo = creditQueryApplyBO.getAnnexBatchNo();
            List<AnnexListVO> annexListVOList = annexListService.getAnnexList(annexBatchNo, AnnexConstant.ANNEX_TYPE_CREDIT);
            if(annexListVOList==null || annexListVOList.size()<3){
                throw new SuzukiCommonException(ErrorCodeEnum.CREDIT_ANNEX_LESS_THREE);
            }
            CreditQueryApplyDO creditQueryApplyDO = new CreditQueryApplyDO();
            BeanCopierUtil.copy(creditQueryApplyBO, creditQueryApplyDO);

            CustomerDO customerDO = new CustomerDO();
            customerDO.setCustomerName(creditQueryApplyBO.getCustomerName());
            customerDO.setIdCardAddr(creditQueryApplyBO.getIdCardAddr());
            LocationBO locationBO = locationService.getIdCardInfo(creditQueryApplyBO.getIdCard());
            customerDO.setIdCardLocation(locationBO.getLocation());
            customerDO.setSex(locationBO.getSex());
            customerDO.setIdCard(creditQueryApplyBO.getIdCard());
            customerDO.setCompanyNo(user.getCompanyNo());
            customerDO.setStaffId(user.getStaffId());
            customerDO.setBemarried(creditQueryApplyBO.getBemarried());
            //客户信息
            customerManager.insertSelective(customerDO);

            creditQueryApplyDO.setCustomerId(customerDO.getCustomerId());
            creditQueryApplyDO.setQueryStatus(CreditStatusEnum.BE_ENTERED.getCode());//默认
            creditQueryApplyDO.setStaffId(user.getStaffId());
            creditQueryApplyDO.setStaffName(user.getStaffName());
            creditQueryApplyDO.setDeptName(user.getDeptName());
            creditQueryApplyDO.setDeptId(user.getDeptId());
            //征信申请dao
            creditQueryApplyManager.insertSelective(creditQueryApplyDO);
            if (AnnexGroupEnum.BUYER.getCode().equals(creditQueryApplyBO.getCustomerType())) {
                //订单信息,只设置主贷人的信息到订单中
                orderDO.setAnnexBatchNo(creditQueryApplyBO.getAnnexBatchNo());
                orderDO.setCustomerName(creditQueryApplyBO.getCustomerName());
                orderDO.setLoanBankName(creditQueryApplyBO.getBankName());
                orderDO.setLoanBankId(creditQueryApplyBO.getBankId());
                orderDO.setCustomerIdCard(creditQueryApplyBO.getIdCard());
                orderDO.setStaffId(user.getStaffId());
                orderDO.setDeptName(user.getDeptName());
                orderDO.setStaffName(user.getStaffName());
                orderDO.setOrderStatus(OrderStatusEnum.CREDITING.getCode());
                orderDO.setTerminalType(terminalType);
                orderDO.setCustomerId(customerDO.getCustomerId());
            }
            OrderCustomerRelDO orderCustomerRelDO = new OrderCustomerRelDO();
            orderCustomerRelDO.setCustomerId(customerDO.getCustomerId());
            orderCustomerRelDO.setCustomerType(creditQueryApplyBO.getCustomerType());//设置角色
            orderCustomerRelDO.setCreditApplyId(creditQueryApplyDO.getCreditQueryApplyId());
            orderCustomerRelDO.setOrderNo(orderNo);
            orderCustomerRelDO.setIsDeleted(IsDeletedEnum.NORMAL.getCode());
            orderCustomerRelManager.insertSelective(orderCustomerRelDO);
        }
        //新建订单dao
        orderManager.insertSelective(orderDO);
    }

    @Override
//    @Cacheable(key="#p0.toString()")
    public PageResult<OrderVO>  queryOrderList(OrderListBO orderListBO) {
        Map<String, Object> paramMap = new HashMap<>(64);
        if(orderListBO.getCustomerIdCard()!=null) {
            paramMap.put("customerIdCard", orderListBO.getCustomerIdCard());
        }
        List<Role> roleList = orderListBO.getRoleList();
        if(roleList != null && roleList.size() > 0) {
            for (Role role : roleList) {
                //如果是业务经理角色ROLE_SALESMANAGER,设置 deptId
                if (RoleTypeEnum.ROLE_SALESMANAGER.getCode().equals(role.getRoleCode())) {
                    paramMap.put("deptId", orderListBO.getDeptId());

                }
                //如果是业务员角色,SPy,设置 staffId
                if (RoleTypeEnum.ROLE_SALESMAN.getCode().equals(role.getRoleCode()) || RoleTypeEnum.ROLE_SPSALESMAN.getCode().equals(role.getRoleCode())) {
                    paramMap.put("staffId", orderListBO.getStaffId());
                }
            }
        }

        paramMap.put("customerId", orderListBO.getCustomerId());
        paramMap.put("staffName", orderListBO.getStaffName());
        paramMap.put("companyNo", orderListBO.getCompanyNo());
        paramMap.put("deptName", orderListBO.getDeptName());
        paramMap.put("gmtCreateBegin", orderListBO.getGmtCreateBegin());
        paramMap.put("gmtCreateEnd", orderListBO.getGmtCreateEnd());
        paramMap.put("orderStatusList", orderListBO.getOrderStatusList());
        paramMap.put("orderStatus", orderListBO.getOrderStatus());
        paramMap.put("loanBankId", orderListBO.getLoanBankId());
        paramMap.put("loanBankIdList", orderListBO.getLoanBankIdList());
        paramMap.put("keyword", orderListBO.getKeyword());

        OrderQuery query = new OrderQuery();
        query.setPageNo(orderListBO.getPageNO());
        query.setPageSize(orderListBO.getPageSize());

        paramMap.put("pageSize", query.getPageSize());
        paramMap.put("pageNO", query.getPageNo());
        paramMap.put("pageOffset", query.getPageOffset());

        PageResult<OrderVO> pageResult = orderManager.selectListByQueryWithPage(paramMap);
        List<OrderVO> orderVOList = pageResult.getResult();
        if (orderVOList != null) {
            for(OrderVO orderVO : orderVOList){
                //订单状态文字描述,页面需要
                orderVO.setOrderStatusDesc(OrderStatusEnum.getOrderStatusEnum(orderVO.getOrderStatus()).getMsg());
            }
        }
        pageResult.setResult(orderVOList);
        pageResult.setPageNo(orderListBO.getPageNO());
        pageResult.setPageSize(orderListBO.getPageSize());
        return pageResult;
    }


    /**
     * 购车人信息查询
     *
     * @param orderNo
     * @return
     * @throws SuzukiCommonException
     **/
    @Override
    public CustomerInfoBO queryCustomerInfo(String orderNo) throws SuzukiCommonException {
        CustomerInfoBO customerInfoBO = new CustomerInfoBO();

        //设置订单信息， 无法联合查询，只能多次查询来获取结果
        OrderInfoBO orderInfoBO = getOrderInfoByOrderNO(orderNo);
        if (orderInfoBO == null) {
            throw new SuzukiCommonException(ErrorCodeEnum.DATA_ERROR);
        }
        customerInfoBO.setOrderInfo(orderInfoBO);

        //获取客户记录id
        Long customerId = orderInfoBO.getCustomerId();
        if (customerId == null) {
            throw new SuzukiCommonException(ErrorCodeEnum.CUSTOMER_IS_NULL);
        }


        //获取客户信息
        CustomerBO customerBO = getCustomerByCustomerId(customerId);
        if (customerBO == null) {//对应客户记录不存在
            throw new SuzukiCommonException(ErrorCodeEnum.CUSTOMER_IS_NULL);
        }
        customerInfoBO.setCustomer(customerBO);

        //获取房产信息
        HouseInfoBO houseInfoBO = getHouseInfoByCustomerId(customerId);
        if(houseInfoBO == null){
            houseInfoBO = new HouseInfoBO();
        }
        customerInfoBO.setHouseInfo(houseInfoBO);

        //获取紧急联系人信息
        List<EmergencyContactBO> emergencyContactBOS = getEmergencyContactsByCustomerId(customerId);
        customerInfoBO.setEmergencyContacts(emergencyContactBOS);

        return customerInfoBO;
    }


    /**
     * 查询共同购车人信息
     *
     * @param orderNo
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    public CustomerBO querySpouseInfo(String orderNo) throws SuzukiCommonException {
        OrderCustomerRelQuery orderCustomerRelQuery = new OrderCustomerRelQuery();
        orderCustomerRelQuery.createCriteria().andOrderNoEqualTo(orderNo)
                .andCustomerTypeEqualTo(CustomerTypeEnum.COMMONBUYER.getCode())
                .andIsDeletedNotEqualTo(IsDeletedEnum.DELETED.getCode());
        List<OrderCustomerRelDO> orderCustomerRelDOS = orderCustomerRelManager.selectByQuery(orderCustomerRelQuery);
        int count = orderCustomerRelDOS.size();
        if (count == 1) {
            Long customerId = orderCustomerRelDOS.get(0).getCustomerId();
            CustomerBO customerBO = getCustomerByCustomerId(customerId);
            if (customerBO == null) {//对应客户记录不存在
                throw new SuzukiCommonException(ErrorCodeEnum.CUSTOMER_IS_NULL);
            }
            return customerBO;
        } else if (count == 0) {//对应共同购车人记录不存在
            /*查询购车人信息*/
            OrderCustomerRelQuery customerRelQuery = new OrderCustomerRelQuery();
            customerRelQuery.createCriteria()
                    .andOrderNoEqualTo(orderNo)
                    .andCustomerTypeEqualTo(CustomerTypeEnum.BUYER.getCode())
                    .andIsDeletedNotEqualTo(IsDeletedEnum.DELETED.getCode());

            List<OrderCustomerRelDO> customerRelDOS = orderCustomerRelManager.selectByQuery(customerRelQuery);
            if(customerRelDOS.size() != 1){
                throw  new SuzukiCommonException(ErrorCodeEnum.DATA_ERROR);
            }

            CustomerDO customerDO = customerManager.selectByPrimaryKey(customerRelDOS.get(0).getCustomerId());
            LocationBO locationBO = locationService.getIdCardInfo(customerDO.getIdCard());
            customerDO.setSex(locationBO.getSex());
            if (Boolean.TRUE.equals(locationBO.getResult())) {
                customerDO.setIdCardLocation(locationBO.getLocation());
            } else {
                customerDO.setIdCardLocation(ErrorCodeEnum.IDCARD_FORMAT_ERROR.getErrMsg());
            }
            //判断购车人是否已婚
            if(BeMarriedEnum.DIVORCED_SINGLE.getCode().equals(customerDO.getBemarried())
                || BeMarriedEnum.SPOUSE_SINGLE.getCode().equals(customerDO.getBemarried())
                || BeMarriedEnum.UNMARRIED_SINGLE.getCode().equals(customerDO.getBemarried())){
                return null;
            } else {
                throw new SuzukiCommonException(ErrorCodeEnum.BE_MARRIED_ERROR);
            }
        } else {//对应共同购车人记录多余一条
            throw new SuzukiCommonException(ErrorCodeEnum.CUSTOMER_TOO_MORE);
        }
    }


    /**
     * 担保人信息查询
     *
     * @param orderNo
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    public List<CustomerDO> queryUnderwriter(String orderNo) throws SuzukiCommonException {

        //符合条件customerID查询
        OrderCustomerRelQuery orderCustomerRelQuery = new OrderCustomerRelQuery();
        orderCustomerRelQuery.createCriteria().andOrderNoEqualTo(orderNo)
                .andCustomerTypeEqualTo(CustomerTypeEnum.SPONSOR.getCode())
                .andIsDeletedNotEqualTo(IsDeletedEnum.DELETED.getCode());
        List<OrderCustomerRelDO> orderCustomerRelDOS = orderCustomerRelManager.selectByQuery(orderCustomerRelQuery);

        if (orderCustomerRelDOS.isEmpty()) {
            return new ArrayList<>();
        }

        //符合多个customerId的结果查询
        CustomerQuery customerQuery = new CustomerQuery();
        for (OrderCustomerRelDO orderCustomerRelDO : orderCustomerRelDOS) {
            customerQuery.or().andCustomerIdEqualTo(orderCustomerRelDO.getCustomerId());
        }
        List<CustomerDO> customerDOS = customerManager.selectByQuery(customerQuery);

        if(!CollectionUtils.isEmpty(customerDOS)) {
            for (CustomerDO customerDO : customerDOS) {
                LocationBO locationBO = locationService.getIdCardInfo(customerDO.getIdCard());
                if (Boolean.TRUE.equals(locationBO.getResult())) {
                    customerDO.setIdCardLocation(locationBO.getLocation());
                    customerDO.setSex(locationBO.getSex());
                } else {
                    customerDO.setIdCardLocation(ErrorCodeEnum.IDCARD_FORMAT_ERROR.getErrMsg());
                }
            }
        }

        if (CollectionUtils.isEmpty(customerDOS)) {
            throw new SuzukiCommonException(ErrorCodeEnum.CUSTOMER_IS_NULL);
        } else if (customerDOS.size() != orderCustomerRelDOS.size()) {
            throw new SuzukiCommonException(ErrorCodeEnum.DATA_ERROR);
        }

        return customerDOS;
    }


    /**
     * 购车人信息录入
     *
     * @param orderNo        订单编号
     * @param customerInfoBO 购车人信息
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void inputCustomerInfo(String orderNo, CustomerInfoBO customerInfoBO) throws SuzukiCommonException {
        Long customerId = customerInfoBO.getCustomer().getCustomerId();
        String customerName = customerInfoBO.getCustomer().getCustomerName();
        if (customerId == null || StringUtils.isBlank(customerName)) {
            throw new SuzukiCommonException(ErrorCodeEnum.PARAM_EMPTY);
        }

        /*订单信息录入*/
        //查询数据库中对应订单信息
        OrderInfoBO queryOrderInfoBO = getOrderInfoByOrderNO(orderNo);
        if (queryOrderInfoBO == null) {
            throw new SuzukiCommonException(ErrorCodeEnum.ORDER_MORE_THAN_ONE);
        }

        //更新订单数据
        OrderInfoBO orderInfoBO = customerInfoBO.getOrderInfo();
        OrderDO orderDO = new OrderDO();
        BeanCopierUtil.copy(orderInfoBO, orderDO);
        OrderQuery orderQuery = new OrderQuery();
        //对应订单修改条件设置
        orderQuery.createCriteria().andOrderNoEqualTo(orderDO.getOrderNo());

        orderManager.updateByQuerySelective(orderDO, orderQuery);

        /*个人信息录入*/

        //数据库中对应个人数据查询
        CustomerBO customerBO = customerInfoBO.getCustomer();
        CustomerBO queryCustomerBO = getCustomerByCustomerId(customerBO.getCustomerId());
        if (queryCustomerBO == null) {//无对应数据
            throw new SuzukiCommonException(ErrorCodeEnum.CUSTOMER_IS_NULL);
        }

        CustomerDO customerDO = new CustomerDO();
        BeanCopierUtil.copy(customerBO, customerDO);
        CustomerQuery customerQuery = new CustomerQuery();
        customerQuery.createCriteria()
                .andCustomerIdEqualTo(customerDO.getCustomerId());
        customerManager.updateByQuerySelective(customerDO, customerQuery);

        /*房产信息录入*/

        //数据库中原有房产信息
        HouseInfoBO queryHouseInfoBO = getHouseInfoByCustomerId(customerId);

        //原房产信息不存在
        if (queryHouseInfoBO == null){
            HouseInfoBO houseInfoBO = customerInfoBO.getHouseInfo();
            HouseInfoDO houseInfoDO = new HouseInfoDO();
            BeanCopierUtil.copy(houseInfoBO, houseInfoDO);
            //首次录入，填入name与id
            houseInfoDO.setCustomerName(customerName);
            houseInfoDO.setCustomerId(customerId);
            long count = houseInfoManager.insertSelective(houseInfoDO);
            if (count != 1L) {
                throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_HOUSE_FAIL);
            }
        } else {//数据库中有房产信息
            HouseInfoBO houseInfoBO = customerInfoBO.getHouseInfo();
            HouseInfoDO houseInfoDO = new HouseInfoDO();
            BeanCopierUtil.copy(houseInfoBO, houseInfoDO);
            HouseInfoQuery houseInfoQuery = new HouseInfoQuery();
            houseInfoQuery.createCriteria().andCustomerIdEqualTo(customerId);
            int count = houseInfoManager.updateByQuerySelective(houseInfoDO, houseInfoQuery);
            if (count != 1) {
                throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_HOUSE_FAIL);
            }
        }


        /*紧急联系人录入*/

        //查询数据库中紧急联系人
        List<EmergencyContactBO> queryEmergencyContactBOS = getEmergencyContactsByCustomerId(customerId);



        //首次插入
        if(queryEmergencyContactBOS.size() != 2){

            //删除原有数据
            EmergencyContactQuery emergencyContactQuery = new EmergencyContactQuery();
            emergencyContactQuery.createCriteria().andCustomerIdEqualTo(customerId);
            emergencyContactManager.deleteByQuery(emergencyContactQuery);

            //插入前端所传数据
            List<EmergencyContactBO> emergencyContactBOS = customerInfoBO.getEmergencyContacts();
            Iterator<EmergencyContactBO> iterator = emergencyContactBOS.iterator();

            while (iterator.hasNext()) {
                EmergencyContactBO emergencyContactBO = iterator.next();
                EmergencyContactDO emergencyContactDO = new EmergencyContactDO();
                BeanCopierUtil.copy(emergencyContactBO, emergencyContactDO);
                emergencyContactDO.setCustomerId(customerId);
                long j = emergencyContactManager.insertSelective(emergencyContactDO);
                if (j != 1L) {
                    throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_EMERGENCY_CONTACT_FAIL);
                }
            }
        } else {//数据库中已有数据
            //判断是否为保存页面重复保存
            boolean repetitionInsert = false;
            List<EmergencyContactBO> emergencyContactBOS = customerInfoBO.getEmergencyContacts();
            Iterator<EmergencyContactBO> iterator = emergencyContactBOS.iterator();
            while (iterator.hasNext()) {
                //数据库中已有数据，且前端所传数据有id为空值，则为保存页面重复保存
                EmergencyContactBO emergencyContactBO = iterator.next();
                if (emergencyContactBO.getEmergencyContactId() == null){
                    repetitionInsert = true;
                }
            }

            if(repetitionInsert){//为重复插入则先删除后添加
                //删除数据库中原有数据
                EmergencyContactQuery emergencyContactQuery = new EmergencyContactQuery();
                emergencyContactQuery.createCriteria().andCustomerIdEqualTo(customerId);
                emergencyContactManager.deleteByQuery(emergencyContactQuery);

                //插入前端所传数据
                for (EmergencyContactBO emergencyContactBO : emergencyContactBOS) {
                    EmergencyContactDO emergencyContactDO = new EmergencyContactDO();
                    BeanCopierUtil.copy(emergencyContactBO, emergencyContactDO);
                    emergencyContactDO.setCustomerId(customerId);
                    long j = emergencyContactManager.insertSelective(emergencyContactDO);
                    if (j != 1L) {
                        throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_EMERGENCY_CONTACT_FAIL);
                    }
                }
            } else {//不为重复插入，只进行更新
                for (EmergencyContactBO emergencyContactBO : emergencyContactBOS) {
                    EmergencyContactDO emergencyContactDO = new EmergencyContactDO();
                    BeanCopierUtil.copy(emergencyContactBO, emergencyContactDO);
                    emergencyContactDO.setCustomerId(customerId);
                    int j = emergencyContactManager.updateByPrimaryKeySelective(emergencyContactDO);
                    if (j != 1) {
                        throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_EMERGENCY_CONTACT_FAIL);
                    }
                }
            }

        }
    }


    /**
     * 共同购车人信息录入
     *
     * @param orderNo
     * @param customerBO
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean inputSpouseInfo(String orderNo, CustomerBO customerBO) throws SuzukiCommonException {
        CustomerDO customerDO = new CustomerDO();
        BeanCopierUtil.copy(customerBO, customerDO);
        if (customerBO.getCustomerId() == null){//共同购车人不存在，直接返回true
            return true;
        }
        CustomerQuery customerQuery = new CustomerQuery();
        customerQuery.createCriteria()
                .andCustomerIdEqualTo(customerBO.getCustomerId());
        int i = customerManager.updateByQuerySelective(customerDO, customerQuery);
        if (i == 1) {
            return true;
        } else {
            throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
        }
    }


    /**
     * 担保人信息录入
     *
     * @param orderNo
     * @param customerBOS
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean inputUnderwriterInfo(String orderNo, List<CustomerBO> customerBOS) throws SuzukiCommonException {
        List<CustomerDO> queryCustomerDOS = queryUnderwriter(orderNo);//订单担保人信息
        if(CollectionUtils.isEmpty(queryCustomerDOS)){//担保人不存在
            log.info("orderNo:{}的担保人不存在", orderNo);
            return true;
        }
        log.debug(JSON.toJSONString(queryCustomerDOS));
        if (queryCustomerDOS.size() == customerBOS.size()) {
            Iterator<CustomerBO> iterator = customerBOS.iterator();
            while (iterator.hasNext()) {
                CustomerBO customerBO = iterator.next();
                CustomerDO customerDO = new CustomerDO();
                BeanCopierUtil.copy(customerBO, customerDO);
                CustomerQuery customerQuery = new CustomerQuery();
                customerQuery.createCriteria().andCustomerIdEqualTo(customerDO.getCustomerId());
                int i = customerManager.updateByQuerySelective(customerDO, customerQuery);
                if (i != 1) {
                    throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
                }
            }
            return true;
        } else {//前后担保人数量不一致
            throw new SuzukiCommonException(ErrorCodeEnum.DATA_ERROR);
        }
    }


    /**
     * 客户信息页面，根据订单号查询订单信息
     *
     * @param orderNo
     * @return
     * @throws SuzukiCommonException
     */
    private OrderInfoBO getOrderInfoByOrderNO(String orderNo) throws SuzukiCommonException {
        OrderInfoBO orderInfoBO = null;
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.createCriteria().andOrderNoEqualTo(orderNo);
        List<OrderDO> orderDOS = orderManager.selectByQuery(orderQuery);
        if (orderDOS.size() == 1) {
            orderInfoBO = new OrderInfoBO();
            BeanCopierUtil.copy(orderDOS.get(0), orderInfoBO);
        } else if (orderDOS.size() > 1) {
            throw new SuzukiCommonException(ErrorCodeEnum.ORDER_MORE_THAN_ONE);
        }
        return orderInfoBO;
    }


    /**
     * 根据客户记录编号查询客户信息
     *
     * @param customerId
     * @return
     */
    private CustomerBO getCustomerByCustomerId(Long customerId){
        CustomerBO customerBO = null;
        CustomerQuery customerQuery = new CustomerQuery();
        customerQuery.createCriteria().andCustomerIdEqualTo(customerId);
        List<CustomerDO> customerDOS = customerManager.selectByQuery(customerQuery);
        if (customerDOS.size() == 1) {//对应客户记录存在
            customerBO = new CustomerBO();
            BeanCopierUtil.copy(customerDOS.get(0), customerBO);
            LocationBO locationBO = locationService.getIdCardInfo(customerBO.getIdCard());
            if (Boolean.TRUE.equals(locationBO.getResult())) {
                customerBO.setIdCardLocation(locationBO.getLocation());
                customerBO.setSex(locationBO.getSex());
            } else {
                customerBO.setIdCardLocation(ErrorCodeEnum.IDCARD_FORMAT_ERROR.getErrMsg());
            }
        }
        return customerBO;
    }


    /**
     * 根据客户记录编号获取房产信息
     *
     * @param customerId
     * @return
     */
    private HouseInfoBO getHouseInfoByCustomerId(Long customerId) throws SuzukiCommonException {
        HouseInfoQuery houseInfoQuery = new HouseInfoQuery();
        houseInfoQuery.createCriteria().andCustomerIdEqualTo(customerId);
        List<HouseInfoDO> houseInfoDOS = houseInfoManager.selectByQuery(houseInfoQuery);
        if (CollectionUtils.isEmpty(houseInfoDOS)){
            return null;
        } else if (houseInfoDOS.size() == 1) {//房产信息可能未添加，也可为一条
            HouseInfoBO houseInfoBO = new HouseInfoBO();
            if(houseInfoDOS.size() == 1){
                BeanCopierUtil.copy(houseInfoDOS.get(0), houseInfoBO);
            }
            return  houseInfoBO;
        } else {
            throw new SuzukiCommonException(ErrorCodeEnum.ORDER_MORE_THAN_ONE);
        }

    }

    /**
     * 根据客户记录编号查询紧急联系人信息
     *
     * @param customerId
     * @return
     */
    private List<EmergencyContactBO> getEmergencyContactsByCustomerId(Long customerId) throws SuzukiCommonException {
        List<EmergencyContactBO> emergencyContactBOS = new ArrayList<>();
        EmergencyContactQuery emergencyContactQuery = new EmergencyContactQuery();
        emergencyContactQuery.createCriteria().andCustomerIdEqualTo(customerId);
        List<EmergencyContactDO> emergencyContactDOS = emergencyContactManager.selectByQuery(emergencyContactQuery);
        if (emergencyContactDOS.size() > 2) {//对应紧急联系人多余两个
            throw new SuzukiCommonException(ErrorCodeEnum.CONTACT_MORE_THAN_TWO);
        } else {
            Iterator<EmergencyContactDO> iterator = emergencyContactDOS.iterator();
            while (iterator.hasNext()) {
                EmergencyContactDO emergencyContactDO = iterator.next();
                EmergencyContactBO emergencyContactBO = new EmergencyContactBO();
                BeanCopierUtil.copy(emergencyContactDO, emergencyContactBO);
                emergencyContactBOS.add(emergencyContactBO);
            }
        }
        return emergencyContactBOS;
    }


    /**
     * 修改订单状态
     * @param orderNo
     * @param orderStatus
     */
    @Override
    public Boolean  changeOrderStatus(String orderNo ,int orderStatus) throws SuzukiCommonException {
        log.info("正在修改订单状态...");
        OrderQuery orderQuery = new OrderQuery();
        OrderDO orderRecord = new OrderDO();
        orderQuery.createCriteria().andOrderNoEqualTo(orderNo);    //订单号
        orderRecord.setOrderStatus(orderStatus);                   //订单状态
        orderManager.updateByQuerySelective(orderRecord,orderQuery);
        log.info("订单状态修改完成...");
        return true;
    }

    /**
     * 查询并获取订单状态
     * @param orderNo
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    public int selectOrderStatus(String orderNo) throws SuzukiCommonException {
        /**查询订单状态**/
        log.info("正在查询订单状态...");
        OrderDO orderInfo = orderManager.selectByOrderNo(orderNo);
        if(orderInfo != null) {
            int orderStatus = orderInfo.getOrderStatus(); //获取当前订单状态
            log.info("当前订单状态为：{}", OrderStatusEnum.getOrderStatusEnum(orderStatus).getMsg());
            return orderStatus;
        }
        throw new SuzukiCommonException(ErrorCodeEnum.SELECT_FAILURE);                    //查询订单状态失败
    }



    /**
     * 根据任务编号查询客户信息
     * @param applyId
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    public AuditCustomerBO getAuditCustomer(Long applyId) throws SuzukiCommonException{
        if (applyId == null) {
            throw new SuzukiCommonException(ErrorCodeEnum.PARAM_EMPTY);
        }
        AuditCustomerBO auditCustomerBO = customerExtMapper.getAuditCustomerBO(applyId);
        if (auditCustomerBO == null) {
            throw new SuzukiCommonException(ErrorCodeEnum.NO_DATA);
        }
        return auditCustomerBO;

    }


    /**
     * 获取历史其他订单记录
     * @param orderListBO
     * @return
     */
    @Override
    public PageResult<OrderVO> queryOtherOrderList(OrderListBO orderListBO) {
        PageResult<OrderVO> orderVOPageResult = this.queryOrderList(orderListBO);
        PageResult<OrderVO> newOrderVOPageResult = new PageResult<>();
        List<OrderVO> orderVOList = orderVOPageResult.getResult();
        List<OrderVO> newOrderVOList = new ArrayList<>();
        if(orderVOList != null && orderVOList.size()>0){
            orderVOList.forEach(orderVO -> {
                if(!orderVO.getOrderNo().equals(orderListBO.getOrderNo())){
                    newOrderVOList.add(orderVO);
                }
            });
        }
        newOrderVOPageResult.setResult(newOrderVOList);
        newOrderVOPageResult.setTotalCount(newOrderVOList.size());
        return newOrderVOPageResult;
    }
}
